package com.zxjbyte.yiyi.framework.web.publisher;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.zxjbyte.yiyi.framework.common.util.EventBusUtil;
import com.zxjbyte.yiyi.framework.common.util.ServletXUtil;
import com.zxjbyte.yiyi.framework.common.util.AuthUtil;
import com.zxjbyte.yiyi.framework.web.event.ErrorLogAddEvent;
import com.zxjbyte.yiyi.module.system.domain.dto.ErrorLogAddDTO;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * 异常信息发送
 * @Author zhangxingjia
 * @Date 2023/3/17 21:31
 * @Version: 1.0
 */
public class ErrorLogPublisher {

    /**
     * 推送消息
     * @param ex
     */
    public static void publishEvent(Throwable ex) {
        ErrorLogAddDTO dto = new ErrorLogAddDTO();
        dto.setUserId(AuthUtil.getUserId());
        dto.setTenantId(AuthUtil.getTenantId());
        dto.setApplicationName(SpringUtil.getApplicationName());
        dto.setExceptionName(ex.getClass().getName());
        dto.setExceptionMessage(ExceptionUtil.getMessage(ex));
        dto.setExceptionRootCauseMessage(ExceptionUtil.getRootCauseMessage(ex));
        dto.setExceptionStackTrace(ExceptionUtil.stacktraceToString(ex, Integer.MAX_VALUE));
        StackTraceElement[] stackTraceElements = ex.getStackTrace();
        if(ArrayUtil.isNotEmpty(stackTraceElements)){
            StackTraceElement stackTraceElement = stackTraceElements[0];
            dto.setExceptionClassName(stackTraceElement.getClassName());
            dto.setExceptionFileName(stackTraceElement.getFileName());
            dto.setExceptionMethodName(stackTraceElement.getMethodName());
            dto.setExceptionLineNumber(stackTraceElement.getLineNumber());
        }
        HttpServletRequest request = ServletXUtil.getRequest();
        if(Objects.nonNull(request)){
            dto.setRequestUrl(request.getRequestURI());
            dto.setRequestParams(ServletXUtil.getRequestContent(request));
            dto.setRequestMethod(request.getMethod());
            dto.setUserAgent(ServletXUtil.getUserAgent(request));
            dto.setUserIp(ServletXUtil.getClientIP(request));
        }
        dto.setExceptionTime(new Date());
        String userName = AuthUtil.getUserName();
        dto.setCreateUser(userName);
        dto.setUpdateUser(userName);
        EventBusUtil.asyncPublishEvent(new ErrorLogAddEvent(dto));
    }
}
